// 通用的服务器状态管理和网络工具函数

export interface ServerStatus {
  running: boolean | null;
  lastChecked: number;
  error?: string;
}

// 通用服务器状态检查
export async function checkServerStatus(
  url: string,
  timeout: number = 3000
): Promise<boolean> {
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), timeout);
    
    const response = await fetch(url, {
      signal: controller.signal,
      headers: {
        'Cache-Control': 'no-cache',
      },
    });
    
    clearTimeout(timeoutId);
    return response.ok;
  } catch (error) {
    if (error instanceof Error) {
      if (error.name === 'AbortError') {
        console.warn('服务器连接超时');
      } else {
        console.warn('服务器连接失败:', error.message);
      }
    }
    return false;
  }
}

// 重试机制包装器
export async function withRetry<T>(
  operation: () => Promise<T>,
  maxRetries: number = 3,
  retryDelay: number = 1000,
  onRetry?: (attempt: number, error: Error) => void
): Promise<T> {
  let lastError: Error;
  
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await operation();
    } catch (error) {
      lastError = error instanceof Error ? error : new Error(String(error));
      
      if (attempt < maxRetries) {
        onRetry?.(attempt, lastError);
        await new Promise(resolve => setTimeout(resolve, retryDelay));
      }
    }
  }
  
  throw lastError!;
}

// 延迟函数
export function delay(ms: number): Promise<void> {
  return new Promise(resolve => setTimeout(resolve, ms));
}

// 批量操作状态统计
export interface BatchStats {
  total: number;
  completed: number;
  failed: number;
  pending: number;
}

export function calculateBatchStats<T extends { status: string }>(items: T[]): BatchStats {
  return {
    total: items.length,
    completed: items.filter(item => item.status === 'confirmed').length,
    failed: items.filter(item => item.status === 'failed').length,
    pending: items.filter(item => item.status === 'pending').length,
  };
}

// 进度计算
export function calculateProgress(current: number, total: number): number {
  if (total === 0) return 0;
  return Math.min(100, Math.max(0, (current / total) * 100));
}

// 通用的网络错误处理
export class NetworkError extends Error {
  constructor(message: string, public status?: number) {
    super(message);
    this.name = 'NetworkError';
  }
}

export function handleNetworkError(error: unknown): never {
  if (error instanceof TypeError && error.message.includes('fetch')) {
    throw new NetworkError('网络连接失败，请检查服务器是否运行');
  }
  
  if (error instanceof Error) {
    throw error;
  }
  
  throw new Error(String(error));
}

// 安全的JSON解析
export async function safeJsonParse<T>(response: Response): Promise<T> {
  const text = await response.text();
  
  try {
    return JSON.parse(text);
  } catch (error) {
    console.error('JSON解析失败:', text);
    console.error('解析错误详情:', error);
    throw new Error('服务器返回了无效的JSON数据');
  }
}

export const checkStorageServerStatus = async (baseUrl: string) => {
  try {
    const response = await fetch(`${baseUrl}/health`, {
      method: 'GET',
      headers: {
        'Cache-Control': 'no-cache',
      },
    });
    
    if (response.ok) {
      return {
        status: 'success',
        message: '服务器运行正常'
      };
    } else {
      return {
        status: 'error',
        message: `服务器响应错误: ${response.status}`
      };
    }
  } catch {
    return {
      status: 'error',
      message: '服务器连接失败'
    };
  }
};
